package com.saleSystem.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.saleSystem.common.ServerResponse;
import com.saleSystem.pojo.TradeHistory;
import com.saleSystem.pojo.User;
import com.saleSystem.service.ITradeHistoryService;
import com.saleSystem.service.IUserService;
import com.saleSystem.vo.BuyProduct;
import com.alibaba.fastjson.JSONArray;

/**
 * 账户管理
 * @author guanwei
 *
 */
@Controller("accountController")
@RequestMapping("/")
public class AccountController {

	private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
	
	@Autowired
	private IUserService iUserService;
	
	@Autowired
	private ITradeHistoryService iTradeHistoryService;
	
	
	/**账务查看
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value="account",method= RequestMethod.GET)
	public String  getAccount(ModelMap map,HttpSession session){
		
		User user = (User)session.getAttribute("user");

		List<TradeHistory> buyList = new ArrayList<TradeHistory>();
		if(user != null){
			buyList = iTradeHistoryService.getAcountInfo(user.getId());
		}
		 
		map.addAttribute("buyList",buyList);
		map.addAttribute("user",user);
		return "account";
	}

	
	@RequestMapping(value="settleAccount",method= RequestMethod.GET)
	public String settleAccount(ModelMap map,HttpSession session){
		

		User user = (User)session.getAttribute("user");
		map.addAttribute("user",user);
		
		return "settleAccount";
	}
	

	
	/**
	 * 购买
	 * @param data
	 * @param session
	 * @return
	 */
	@RequestMapping(value="api/buy",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public ServerResponse<Boolean> buyProductTest(@RequestBody String data,HttpSession session){
		
		logger.info("要购买的产品ID及数量：" + data);
        List<BuyProduct> buyList=new ArrayList<BuyProduct>(JSONArray.parseArray(data,BuyProduct.class));
        
        System.out.println(buyList);
/*		String username = (String)session.getAttribute("userName");
		logger.info("用户：" + username);
		User user = iUserService.getUser(username);*/
		User user = (User)session.getAttribute("user");
		ServerResponse<Boolean> response = iTradeHistoryService.insertTradeHistory(buyList, user==null ? null:user.getId());
		return response;
	}
	
}
